import unittest
import os,time,sys
import os.path
sys.path.append(os.path.abspath('..'))
from service.pconfig import PConfig
from service.PlusterLog import PlusterLog
from service.rrd import Rrd
from service.exception import *
import logging

class TestRrd(unittest.TestCase):
    "Test Rrd class"

    def setUp(self):
        logging.basicConfig()
        if not os.path.exists('pluster.cfg'):
            f=open('pluster.cfg','a')
            cfg="""[cluster]
mail = pluster.mail@gmail.com
name = ziqiang3000
passwd = pluster.
send_to = hide1713@gmail.com
smtp = smtp.gmail.com
total_node = 210

[debug]
debuglevel = 0

[logger]
file_name = ./log/msg.log
file_on = false
file_size_limit = 2000
mail_on = false
view_limit = 1000

[main_server]
address = 127.0.0.1
net = lo
port = 8888

[node]
net = lo
port = 7999

[rrd]
rrd_path = ./rrd/

[user]
root = No Description
ziqiang3000 = Cluster

[xmlrpc]
port_start = 8888
reuse = true
task_poolsize = 10
"""
            f.write(cfg)
            f.close()
        if not os.path.exists('log/msg.log'):
            try:
                os.mkdir('log')
            except:
                pass
            l=open('log/msg.log','w')
            l.close()
        self.c=PConfig()
        self.r=Rrd()

    def test_draw(self):
        self.assertRaises(RrdFileNotFoundError,self.r.draw_node,\
                             "foo","-1h","now","full")
        self.assertRaises(RrdNoUserError,self.r.draw_user,\
                             "bar","-1h","now" )
        self.r.create_node('cn54')
        self.r.create_user('hide')
        self.r.draw_node("cn54","-1h","now","full")
        self.r.draw_node("cn54","-1h","now","icon")
        self.r.draw_user("hide","-1h","now")


    def test_create_rrd(self):
        "Test create node and user rrd"
        self.r.create_node("cn54")
        self.r.create_user("hide")
        self.assertTrue(os.path.exists('./rrd/cn54.rrd'))
        self.assertTrue(os.path.exists('./rrd/hide.rrd'))

    def test_update(self):
        "Test Update data into user and node rrd"
        self.r.create_node('cn54')
        self.r.create_user('hide')
        self.r.remove_node('cn54')
        self.r.remove_user('hide')

        self.assertRaises(RrdFileNotFoundError,self.r.update_node,\
                             "cn54",23.3,12.2,100,200 )
        self.assertRaises(RrdNoUserError,self.r.update_user,\
                             "hide",11.2,10.3,3)

        self.r.create_node('cn54')
        self.r.create_user('hide')
        self.r.update_node("cn54",23.3,12.2,100,200)
        self.r.update_user("hide",11.2,10.3,3)


    def tearDown (self):
        """ Clean up rrd"""
        if os.path.exists('log/msg.log'):
            os.remove('log/msg.log')
            os.rmdir('log')
        os.remove('./rrd/hide.rrd')
        os.remove('./rrd/cn54.rrd')



if __name__=="__main__":
    unittest.main()
